package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerLoginService;
import com.dongdongshop.shiro.ShiroConfig;
import com.dongdongshop.shiro.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@Controller
public class SellerLoginController {

    @DubboReference
    private SellerLoginService sellerLoginService;

    @RequestMapping("shoplogin")
    private String shoplogin() {
        return "shoplogin";
    }
    @RequestMapping("index")
    private String index() {
        return "admin/index";
    }

    @RequestMapping("register")
    private String register() {
        return "register";
    }

    @RequestMapping("toregister")
    @ResponseBody
    private Result toregister(TbSeller tbSeller) {
        String salt = ShiroUtils.generateSalt(6);
        String pwd = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), salt, 3);
        tbSeller.setPassword(pwd);
        tbSeller.setSalt(salt);
        tbSeller.setStatus("0");
        boolean b = sellerLoginService.insert(tbSeller);
        if (b){
            return Result.response(ResultEnum.SUCCESS);
        }
        return Result.response(ResultEnum.ERROR);
    }

    @RequestMapping("getSellerLogin")
    @ResponseBody
    private Result getSellerLogin(TbSeller tbSeller, HttpServletRequest request){
        //1.创建subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户的账号密码  token对象
        UsernamePasswordToken token = new UsernamePasswordToken(tbSeller.getSellerId(), tbSeller.getPassword());
        //3.执行登录功能

        //shiro是通过抛出异常的方式来提示账号不存在或者密码错误
        try {
            subject.login(token);
        }catch (UnknownAccountException e) {
            //账号不存在
            return Result.response(ResultEnum.ERROR);
        }catch (IncorrectCredentialsException e) {
            //密码错误
            return Result.response(ResultEnum.ERROR);
        } catch (LoginException e){
            //状态错误
            return Result.response(ResultEnum.EXMAIN);
        }
        //登录成功
        request.getSession().setAttribute("tbSeller",tbSeller);
        return Result.response(ResultEnum.SUCCESS);
    }
}
